package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.domain.vo.VideoVo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.lang.invoke.VolatileCallSite;
import java.util.ArrayList;
import java.util.List;

@Service
public class VideoManager {

    @Reference
    private VideoService videoService;

    @Reference
    private UserInfoService userInfoService;

    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private FastFileStorageClient client;  //存储的客户端  注入会报错 , 不影响执行
    @Autowired
    private FdfsWebServer webServer; // tracker的服务器  注入会报错 , 不影响执行
    /**
     * 查询小视频列表
     * @param pageNumber
     * @param pageSize
     * @return
     */
    @Cacheable(value="video" , key="'video_'+#pageNumber+'_'+#pageSize")
    public PageBeanVo findVideo(Integer pageNumber, Integer pageSize) {
        //1.获得当前用户id
        Long loginUserId = UserHolder.getId();

        //2.查询小视频的列表
        PageBeanVo  pageBeanVo = videoService.findVideoByUserId(pageNumber , pageSize , loginUserId);

        List<Video> items = (List<Video>) pageBeanVo.getItems(); //可以设置假数据
        List<VideoVo> videoVoList = new ArrayList();
        //3.封装vo  items - >  videoVoList
        if(CollectionUtil.isNotEmpty(items)){
            for (Video video : items) {
                //3.1.查询到个人信息
                UserInfo userInfo = userInfoService.findById(video.getUserId());
                //3.2 创建vo对象
                VideoVo videoVo = new VideoVo();
                //3.3 封装UserInfo userId封装不了
                BeanUtil.copyProperties(userInfo ,videoVo );
                //videoVo.setUserId( userInfo.getId() ); //手动赋值 用户的id

                //3.4 封装video
                BeanUtil.copyProperties(video , videoVo);
                videoVo.setCover(video.getPicUrl()); //封面
                videoVo.setVideoUrl(video.getVideoUrl()); //视频
                videoVo.setSignature( video.getText() );//文本 标题

                //设置是否关注
                String key = StrUtil.format(ConstantUtil.FOCUS_USER , UserHolder.getId()  , video.getUserId() );
                if(stringRedisTemplate.hasKey(key)){ //关注过
                    videoVo.setHasFocus(1);
                }

                videoVoList.add(videoVo);
            }
        }

        pageBeanVo.setItems(videoVoList);
        return pageBeanVo;
    }
    /**
     * 保存小视频
     * @param videoThumbnail
     * @param videoFile
     */
    @CacheEvict(value = "video" , allEntries = true)
    public void saveVideo(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1.保存封面 -oss
        String picUrl = "https://"+ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //2.保存视频 -fastDFS
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), FileUtil.extName(videoFile.getOriginalFilename()), null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();//拼接文件路径
        System.err.println("------->>>"+videoUrl);
        //3.构建Video对象
        Video video = new Video();
        video.setUserId(UserHolder.getId());//当前登录用户
        video.setText("左手右手一个慢动作!");
        video.setPicUrl(picUrl); //封面路径
        video.setVideoUrl(videoUrl);//视频路径
        //4.保存数据
        videoService.saveVideo(video);
    }
    /**
     * 删除视频关注
     * @param videoUserId
     */
    @CacheEvict(value = "video" , allEntries = true)
    public void deleteUserFocus(Long videoUserId) {
        //当前用户id
        Long loginUserId = UserHolder.getId();

        //删除记录
        focusUserService.deleteUserFocus(loginUserId , videoUserId);

        //删除缓存
        String key = StrUtil.format(ConstantUtil.FOCUS_USER , UserHolder.getId()  , videoUserId );
        stringRedisTemplate.delete(key);
    }

    @Reference
    private FocusUserService focusUserService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 添加视频关注
     * @param videoUserId
     */
    @CacheEvict(value = "video" , allEntries = true)
    public void saveUserFocus(Long videoUserId) {
        //构建对象
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(UserHolder.getId());//自己的id
        focusUser.setFocusUserId(videoUserId); //视频发布者的id

        //直接保存
        focusUserService.saveUserFocus(focusUser);

        //存入缓存中
        // 谁关注了谁  99_2
        String key = StrUtil.format(ConstantUtil.FOCUS_USER , UserHolder.getId()  , videoUserId );
        stringRedisTemplate.opsForValue().set(key , "1");

    }
}
